package com.topscore.uke.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.topscore.uke.R;
import com.topscore.uke.entities.CityBean;
import com.topscore.uke.entities.DistrictBean;
import com.topscore.uke.entities.ProvinceBean;
import com.topscore.uke.entities.ProvinceJsonData;
import com.topscore.uke.mvp.contractors.GetDistrictInfoContractor;
import com.topscore.uke.mvp.presenters.GetDistrictInfoPresenter;
import com.topscore.utillibrary.widget.wheelview.ArrayWheelAdapter;
import com.topscore.utillibrary.widget.wheelview.WheelView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by 71468 on 2017/9/19.
 */

public class CitySelector extends Dialog implements GetDistrictInfoContractor.View {
    @Bind(R.id.cancel_btn)
    TextView cancelBtn;
    @Bind(R.id.confirm_btn)
    TextView confirmBtn;
    @Bind(R.id.province_wheel)
    WheelView provinceWheel;
    @Bind(R.id.city_wheel)
    WheelView cityWheel;
    @Bind(R.id.district_wheel)
    WheelView districtWheel;

    private List<String> mProvinceNameList, mCityNameList, mDistrictNameList;

    private List<ProvinceBean> mProvinceList;
    private List<CityBean> mCityList;
    private List<DistrictBean> mDistrictList;

    private HashMap<ProvinceBean, List<CityBean>> mProvinceToCitiesMap;

    private Context mContext;

    private OnCitySelectListener mOnCitySelectListener;

    private GetDistrictInfoContractor.Presenter mGetDistrictPresenter;

    public CitySelector(@NonNull Context context) {
        super(context);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();

        window.setWindowAnimations(R.style.DialogBottomAnimation);
        window.setGravity(Gravity.BOTTOM);
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.citiy_selector_layout);
        ButterKnife.bind(this);
        mGetDistrictPresenter = new GetDistrictInfoPresenter(this);
        initViews();
    }

    private void initViews() {
        provinceWheel.setCyclic(false);
        cityWheel.setCyclic(false);
        districtWheel.setCyclic(false);
        provinceWheel.setOnItemSelectedListener(index -> {
            mCityNameList = new ArrayList<>();
            mCityList = mProvinceToCitiesMap.get(mProvinceList.get(index));
            for (int i = 0; i < mCityList.size(); i++) {
                mCityNameList.add(mCityList.get(i).getCityName());
            }
            cityWheel.setAdapter(new ArrayWheelAdapter((ArrayList<String>) mCityNameList));
            cityWheel.setCurrentItem(0);
            mGetDistrictPresenter.getDistrictInfo(mCityList.get(0).getCityCode());
        });

        cityWheel.setOnItemSelectedListener(index -> {
            CityBean cityBean = mCityList.get(index);
            mGetDistrictPresenter.getDistrictInfo(cityBean.getCityCode());
        });

        cancelBtn.setOnClickListener(v -> dismiss());
        confirmBtn.setOnClickListener(v -> {
            if (mOnCitySelectListener != null) {
                ProvinceBean province = mProvinceList.get(provinceWheel.getCurrentItem());
                CityBean cityBean = mProvinceToCitiesMap.get(province).get(cityWheel.getCurrentItem());
                DistrictBean districtBean = mDistrictList.get(districtWheel.getCurrentItem());
                mOnCitySelectListener.onSelected(province, cityBean, districtBean);
                dismiss();
            }
        });

        initData();

    }

    private void initData() {
        AssetManager assetManager = mContext.getAssets();
        InputStream inputStream;
        try {
            inputStream = assetManager.open("province.json");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            String json = new String(buffer, "utf-8");
            inputStream.close();
            ProvinceJsonData data = new Gson().fromJson(json, ProvinceJsonData.class);
            mProvinceList = data.getProvince();
            mProvinceToCitiesMap = new HashMap<>();
            mProvinceNameList = new ArrayList<>();
            for (int i = 0; i < mProvinceList.size(); i++) {
                ProvinceBean bean = mProvinceList.get(i);
                mProvinceToCitiesMap.put(bean, bean.getCity());
                mProvinceNameList.add(mProvinceList.get(i).getProvinceName());
            }
            mCityList = mProvinceToCitiesMap.get(mProvinceList.get(0));
            mCityNameList = new ArrayList<>();
            for (int i = 0; i < mCityList.size(); i++) {
                mCityNameList.add(mCityList.get(i).getCityName());
            }
            mDistrictList = mCityList.get(0).getArea();
            mDistrictNameList = new ArrayList<>();
            for (int i = 0; i < mDistrictList.size(); i++) {
                mDistrictNameList.add(mDistrictList.get(i).getAreaName());
            }
            provinceWheel.setAdapter(new ArrayWheelAdapter((ArrayList<String>) mProvinceNameList));
            cityWheel.setAdapter(new ArrayWheelAdapter((ArrayList<String>) mCityNameList));
            districtWheel.setAdapter(new ArrayWheelAdapter((ArrayList<String>) mDistrictNameList));
            provinceWheel.setCurrentItem(0);
            cityWheel.setCurrentItem(0);
            districtWheel.setCurrentItem(0);
            mGetDistrictPresenter.getDistrictInfo(mCityList.get(0).getCityCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void show() {
        super.show();
        Window win = this.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
    }

    public CitySelector setOnCitySelectListener(OnCitySelectListener onCitySelectListener) {
        this.mOnCitySelectListener = onCitySelectListener;
        return this;
    }

    @Override
    public void onLoading(String loadingMessage) {

    }

    @Override
    public void onLoadFinished() {

    }

    @Override
    public void onFail(int code, String errorMessage) {
        Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetDistrictInfoSuccess(List<DistrictBean> districtBeanList) {
        mDistrictList = districtBeanList;
        mDistrictNameList = new ArrayList<>();
        for (int i = 0; i < mDistrictList.size(); i++) {
            mDistrictNameList.add(mDistrictList.get(i).getAreaName());
        }
        districtWheel.setAdapter(new ArrayWheelAdapter((ArrayList<String>) mDistrictNameList));
        districtWheel.setCurrentItem(0);
    }

    public interface OnCitySelectListener {
        void onSelected(ProvinceBean province, CityBean city, DistrictBean district);
    }
}
